<template>
  <div class="w-full max-w-md">
    <form @submit.prevent="handleLogin" class="rounded-xl overflow-hidden transform transition-all duration-500 hover:shadow-xl bg-white/90 backdrop-blur-sm">
      <div class="px-8 pt-8 pb-6">
        <h2 class="text-2xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-[#8153ff] to-[#93dc24] mb-6 text-center animate-fade-in-up" style="--delay: 100ms;">欢迎回来</h2>
        
        <!-- 邮箱输入框 -->
        <div class="mb-5 group animate-fade-in-up" style="--delay: 200ms;">
          <label for="email" class="block text-sm font-medium text-gray-700 mb-1 group-focus-within:text-[#8153ff] transition-colors duration-300">邮箱</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400 group-focus-within:text-[#8153ff] transition-colors duration-300">
              <font-awesome-icon icon="envelope" class="transform group-focus-within:scale-110 transition-all duration-300" />
            </div>
            <input
              id="email"
              v-model="email"
              type="email"
              required
              class="form-input pl-10 w-full px-3 py-3.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-[#8153ff]/60 focus:border-[#8153ff] transition-all duration-500 ease-spring"
              placeholder="请输入您的邮箱"
              :class="{ 'border-red-500 focus:ring-red-500 focus:border-red-500': errors.email }"
            />
            <div v-if="email" 
                class="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity duration-200"
                @click="email = ''">
              <font-awesome-icon icon="times-circle" class="text-gray-400 hover:text-[#8153ff] transition-colors duration-300 transform hover:scale-110" />
            </div>
          </div>
          <p v-if="errors.email" class="mt-1 text-sm text-red-500 flex items-center animate-fade-in">
            <font-awesome-icon icon="exclamation-circle" class="mr-1" />
            {{ errors.email }}
          </p>
        </div>
        
        <!-- 密码输入框 -->
        <div class="mb-5 group animate-fade-in-up" style="--delay: 300ms;">
          <label for="password" class="block text-sm font-medium text-gray-700 mb-1 group-focus-within:text-[#8153ff] transition-colors duration-300">密码</label>
          <div class="relative">
            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-gray-400 group-focus-within:text-[#8153ff] transition-colors duration-300">
              <font-awesome-icon icon="lock" class="transform group-focus-within:scale-110 transition-all duration-300" />
            </div>
            <input
              id="password"
              v-model="password"
              :type="showPassword ? 'text' : 'password'"
              required
              class="form-input pl-10 w-full px-3 py-3.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-[#8153ff]/60 focus:border-[#8153ff] transition-all duration-500 ease-spring"
              placeholder="请输入您的密码"
              :class="{ 'border-red-500 focus:ring-red-500 focus:border-red-500': errors.password }"
            />
            <div 
              class="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer"
              @click="togglePasswordVisibility"
            >
              <font-awesome-icon 
                :icon="showPassword ? 'eye-slash' : 'eye'" 
                class="text-gray-400 hover:text-[#8153ff] transition-colors duration-300 transform hover:scale-110"
              />
            </div>
          </div>
          <p v-if="errors.password" class="mt-1 text-sm text-red-500 flex items-center animate-fade-in">
            <font-awesome-icon icon="exclamation-circle" class="mr-1" />
            {{ errors.password }}
          </p>
        </div>
        
        <!-- 记住我和忘记密码 -->
        <div class="flex items-center justify-between mb-6 animate-fade-in-up" style="--delay: 400ms;">
          <div class="flex items-center">
            <div class="relative inline-block w-10 mr-2 align-middle select-none transition duration-300 ease-in">
              <input 
                type="checkbox" 
                id="remember-me" 
                v-model="rememberMe" 
                class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer transition-all duration-300 ease-spring"
                :class="{ 'border-[#8153ff]': rememberMe }"
              />
              <label 
                for="remember-me" 
                class="toggle-label block h-5 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300 ease-spring"
                :class="{ 'bg-[#8153ff]/20': rememberMe }"
              ></label>
            </div>
            <label for="remember-me" class="text-sm text-gray-700 cursor-pointer">记住我</label>
          </div>
          <div class="text-sm">
            <a href="#" class="font-medium text-[#8153ff] hover:text-[#93dc24] transition-all duration-300 relative group">
              忘记密码?
              <span class="absolute bottom-0 left-0 w-0 h-0.5 bg-[#93dc24] group-hover:w-full transition-all duration-300 ease-spring opacity-70"></span>
            </a>
          </div>
        </div>
        
        <!-- 登录按钮 -->
        <button
          type="submit"
          class="w-full flex justify-center items-center px-4 py-3.5 bg-gradient-to-r from-[#8153ff] to-[#93dc24] text-white rounded-xl shadow-md hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#8153ff] transition-all duration-500 transform hover:translate-y-[-2px] active:translate-y-[1px] group overflow-hidden relative animate-fade-in-up ease-spring"
          :disabled="isLoading"
          style="--delay: 500ms;"
        >
          <span class="absolute inset-0 w-full h-full bg-gradient-to-r from-[#93dc24] to-[#8153ff] opacity-0 group-hover:opacity-100 transition-opacity duration-500"></span>
          <span v-if="isLoading" class="mr-2 relative z-10">
            <svg class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
          </span>
          <font-awesome-icon v-else icon="right-to-bracket" class="mr-2 relative z-10 group-hover:scale-110 transition-transform duration-300" />
          <span class="relative z-10">
            {{ isLoading ? '登录中...' : '登录' }}
            <span v-if="!isLoading" class="absolute bottom-0 left-0 w-0 border-b-2 border-white group-hover:w-full transition-all duration-500 ease-spring"></span>
          </span>
        </button>
      </div>
      
      <!-- 注册链接 -->
      <div class="px-8 py-5 border-t border-gray-100/50 flex justify-center animate-fade-in-up" style="--delay: 600ms;">
        <p class="text-sm text-gray-600">
          还没有账号?
          <router-link to="/register" class="font-medium text-[#8153ff] hover:text-[#93dc24] transition-all duration-300 relative group">
            立即注册
            <span class="absolute bottom-0 left-0 w-0 h-0.5 bg-[#93dc24] group-hover:w-full transition-all duration-300 ease-spring opacity-70"></span>
          </router-link>
        </p>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../../stores/userStore';
import { authAPI } from '../../services/api';
import { toast } from '../../services/toastService';

const router = useRouter();
const userStore = useUserStore();

// 表单数据
const email = ref('');
const password = ref('');
const rememberMe = ref(false);
const showPassword = ref(false);
const isLoading = ref(false);
const errors = reactive({
  email: '',
  password: '',
  server: ''
});

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

// 表单验证
const validateForm = () => {
  let isValid = true;
  
  // 重置错误
  errors.email = '';
  errors.password = '';
  errors.server = '';
  
  // 验证邮箱
  if (!email.value) {
    errors.email = '请输入邮箱';
    isValid = false;
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.value)) {
    errors.email = '请输入有效的邮箱地址';
    isValid = false;
  }
  
  // 验证密码
  if (!password.value) {
    errors.password = '请输入密码';
    isValid = false;
  } else if (password.value.length < 6) {
    errors.password = '密码长度不能少于6个字符';
    isValid = false;
  }
  
  return isValid;
};

// 处理登录
const handleLogin = async () => {
  if (!validateForm()) return;
  
  try {
    isLoading.value = true;
    
    const response = await authAPI.login({
      email: email.value,
      password: password.value
    });
    
    // 登录用户 - 使用更新后的方法，传递token参数
    userStore.loginUser({
      id: response.user.id,
      email: response.user.email,
      username: response.user.username
    }, response.token);
    
    // 根据"记住我"设置存储凭据
    if (rememberMe.value) {
      localStorage.setItem('rememberedEmail', email.value);
    } else {
      localStorage.removeItem('rememberedEmail');
    }
    
    // 显示成功消息
    toast.success('登录成功！正在跳转到主页...', 2000);
    
    // 登录成功后重定向到首页，稍微延迟以便用户看到成功提示
    setTimeout(() => {
      router.push('/home');
    }, 1500);
  } catch (error) {
    console.error('登录失败:', error);
    
    // 提取错误消息
    const errorMsg = error.message || '登录失败，请检查您的邮箱和密码';
    
    // 针对特定的登录失败情况，显示更明确的错误信息
    if (errorMsg.includes('邮箱或密码不正确')) {
      errors.email = '邮箱或密码不正确';
      errors.password = '邮箱或密码不正确';
      // 显示带有特殊标记的错误弹窗，使其更加醒目
      toast.error('⚠️ 邮箱或密码不正确，请重新输入', 5000);
    } else {
      // 其他类型的错误
      toast.error(errorMsg, 4000);
      errors.server = errorMsg;
    }
    
    // 轻微振动输入框，提供视觉反馈
    if (errorMsg.includes('邮箱或密码不正确')) {
      const emailInput = document.getElementById('email');
      const passwordInput = document.getElementById('password');
      
      if (emailInput) emailInput.classList.add('shake-error');
      if (passwordInput) passwordInput.classList.add('shake-error');
      
      // 移除动画类，以便下次可以再次触发
      setTimeout(() => {
        if (emailInput) emailInput.classList.remove('shake-error');
        if (passwordInput) passwordInput.classList.remove('shake-error');
      }, 500);
    }
  } finally {
    isLoading.value = false;
  }
};

// 初始化 - 检查是否有保存的邮箱
const initForm = () => {
  const rememberedEmail = localStorage.getItem('rememberedEmail');
  if (rememberedEmail) {
    email.value = rememberedEmail;
    rememberMe.value = true;
  }
};

initForm();
</script>

<style scoped>
/* 切换开关容器样式 */
.relative.inline-block.w-10 {
  position: relative;
  display: inline-block;
  width: 2.5rem; /* 40px, 等同于w-10 */
  height: 1.25rem; /* 20px, 刚好适合开关高度 */
  overflow: hidden; /* 防止内容溢出 */
}

/* 切换开关样式 */
.toggle-checkbox {
  position: absolute; /* 确保绝对定位 */
  left: 0; /* 初始位置 */
  top: 0; /* 垂直居中 */
  margin: 0; /* 移除默认边距 */
  z-index: 1; /* 确保复选框在上层 */
  transition: all 0.3s ease-in-out; /* 平滑过渡 */
}

.toggle-checkbox:checked {
  left: calc(100% - 1.25rem); /* 激活时向右移动，保留5px高度 */
  border-color: #8153ff;
}

.toggle-label {
  display: block;
  width: 100%; /* 占满容器宽度 */
  height: 100%; /* 占满容器高度 */
  position: relative; /* 相对定位 */
  border-radius: 9999px; /* 圆角 */
  transition: all 0.3s ease-in-out; /* 平滑过渡 */
}

.toggle-checkbox:checked + .toggle-label {
  background-color: #f0ebff;
}

/* 输入框焦点缩放效果 */
.form-input:focus {
  transform: scale(1.01);
  box-shadow: 0 0 15px rgba(129, 83, 255, 0.15);
}

/* 按钮禁用状态 */
button:disabled {
  @apply opacity-70 cursor-not-allowed transform-none shadow-none;
}

/* 错误抖动动画 */
@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-3px); }
  20%, 40%, 60%, 80% { transform: translateX(3px); }
}

.shake-error {
  animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
  border-color: #ef4444 !important;
  background-color: rgba(254, 226, 226, 0.1) !important;
  box-shadow: 0 0 0 1px rgba(239, 68, 68, 0.2) !important;
}

/* 弹性动画 */
.ease-spring {
  transition-timing-function: cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 淡入动画 */
.animate-fade-in-up {
  opacity: 0;
  transform: translateY(15px);
  animation: fade-in-up 0.8s cubic-bezier(0.34, 1.56, 0.64, 1) forwards;
  animation-delay: var(--delay, 0ms);
}

@keyframes fade-in-up {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fade-in {
  animation: fade-in 0.3s ease forwards;
}

@keyframes fade-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 表单整体样式 */
form {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
}

form:hover {
  box-shadow: 0 15px 60px rgba(129, 83, 255, 0.15);
  transform: translateY(-5px);
}
</style> 